import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse, Axios, InternalAxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'
import useGlobalStore from '@/store/modules/global'

const BASE_URL = 'https://mu-api.yuk0.com/'
function createAxiosInstance() {
    const instance = axios.create({
        baseURL: '/dev-api',
        timeout: 10000,
    })
    instance.interceptors.response.use((response: AxiosResponse) => {
        return response.data
    }, error => {
        console.log('出错了');
        throw error
    })

    return instance
}
// 没有loading的实例
const requestWithoutLoading = createAxiosInstance()
// 有loading的实例
const instance = createAxiosInstance()
useLoading(instance.interceptors)

// loading实例
let loading
// loading调用计数器
let loadingCount = 0
function useLoading(interceptors: Axios['interceptors']) {
    interceptors.request.use(loadingRequestInterceptor)
    interceptors.response.use(loadingResponseInterceptor, loadingResponseErrorInterceptor)
}
function loadingRequestInterceptor(config: InternalAxiosRequestConfig) {
    if (!loading) {
        loading = ElLoading.service({
            // lock: true,
            text: '载入中',
            spinner: 'el-icon-loading',
            background: 'transparent',
        })
        useGlobalStore().setLoading(true)
    }
    loadingCount++
    return config
}
function loadingResponseInterceptor(response) {
    handleResponseLoading()
    return response

}
function loadingResponseErrorInterceptor(error) {
    handleResponseLoading()
    throw error
}

function handleResponseLoading() {
    loadingCount--
    if (loadingCount == 0) {
        loading.close()
        loading = null
        useGlobalStore().setLoading(false)
    }
}
export function request<T>(config: AxiosRequestConfig) {
    return instance<any, T>(config)
}
export default request